import * as fs from "fs"
import initSqlJs from "sql.js"
import * as path from "path"

export class CursorUserChanger {
  /**
   * 修改Cursor用户信息
   */
  async changeCursorUser(dbPath: string, email: string, accessToken: string): Promise<boolean> {
    console.log("=== CursorUserChanger.changeCursorUser 开始 ===")
    console.log("dbPath:", dbPath)
    console.log("email:", email)

    try {
      // 初始化sql.js
      const SQL = await initSqlJs({
        locateFile: (file: string) => {
          const wasmPath = path.join(__dirname, "..", "node_modules", "sql.js", "dist", file)
          console.log("WASM文件路径:", wasmPath)
          return wasmPath
        }
      })

      // 读取数据库
      if (!fs.existsSync(dbPath)) {
        throw new Error(`数据库文件不存在: ${dbPath}`)
      }

      const dbBuffer = fs.readFileSync(dbPath)
      const db = new SQL.Database(dbBuffer)

      // 设置要更新的键值对
      const updates = [
        { key: "cursorAuth/cachedSignUpType", value: "Auth_0" },
        { key: "cursorAuth/cachedEmail", value: email },
        { key: "cursorAuth/accessToken", value: accessToken },
        { key: "cursorAuth/refreshToken", value: accessToken },
        { key: "cursorAuth/stripeMembershipType", value: "free_trial" },
        { key: "cursorAuth/stripeSubscriptionStatus", value: "trialing" }
      ]

      for (const { key, value } of updates) {
        console.log(`开始处理键值对: ${key}`)

        // 强制更新策略：先删除旧记录（如果存在），再插入新记录
        // DELETE操作在记录不存在时不会报错，只是删除0行，所以初始化为空时也安全

        // 第一步：检查旧记录是否存在
        const checkOld = db.exec("SELECT value FROM ItemTable WHERE key = ?", [key])
        const isUpdate = checkOld.length > 0 && checkOld[0].values.length > 0

        if (isUpdate) {
          const oldValue = checkOld[0].values[0][0]
          console.log(`发现旧记录: ${key}，旧值: ${oldValue}`)
        } else {
          console.log(`旧记录不存在，将创建新记录: ${key}`)
        }

        // 第二步：删除旧记录（如果存在）
        // DELETE不会因为记录不存在而报错
        db.exec("DELETE FROM ItemTable WHERE key = ?", [key])

        // 第三步：插入新记录
        db.exec("INSERT INTO ItemTable (key, value) VALUES (?, ?)", [key, value])
        console.log(`已插入新记录: ${key}`)

        // 第四步：验证插入是否成功，确保值完全正确
        const verifyResult = db.exec("SELECT value FROM ItemTable WHERE key = ?", [key])

        if (verifyResult.length === 0 || verifyResult[0].values.length === 0) {
          throw new Error(`强制更新失败：记录不存在 - ${key}`)
        }

        const actualValue = verifyResult[0].values[0][0]
        if (actualValue !== value) {
          throw new Error(
            `强制更新失败：值不匹配 - ${key}\n期望值: ${value}\n实际值: ${actualValue}`
          )
        }

        const keyName = key.split("/").pop() || key
        console.log(`✓ ${isUpdate ? "更新" : "创建"}成功: ${keyName}`)
      }

      // 保存数据库
      const data = db.export()
      fs.writeFileSync(dbPath, Buffer.from(data))

      db.close()
      console.log("=== 数据库更新成功 ===")
      return true
    } catch (error) {
      console.error("=== 修改用户信息失败 ===")
      console.error("错误详情:", error)
      throw error
    }
  }
}
